package com.tjcd.project.library_base.push.mqtt;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.IBinder;
import android.provider.Settings;

import androidx.annotation.Nullable;
import androidx.work.BackoffPolicy;
import androidx.work.Constraints;
import androidx.work.ExistingPeriodicWorkPolicy;
import androidx.work.NetworkType;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager;

import com.blankj.utilcode.util.LogUtils;
import com.tjcd.project.library_base.R;

import java.util.concurrent.TimeUnit;

/**
 * @Author jiangKunKun
 * @CreateDate 2021/7/12
 * @Description MQTT 服务类，用于管理 MQTT 连接和保活
 * @SpittingGrooves
 */
public class MqttService extends Service {
    /**
     * 前台服务Id
     */
    private final int GRAY_SERVICE_ID = 0x1210;
    /**
     * channelid
     */
    private String CHANNEL_ONE_ID = "channel_one_id";
    /**
     * 用于管理 MQTT 连接。
     */
    private MqttManager mqttManager;

    /**
     * 8.0前台服务兼容
     *
     * @param text
     * @param code
     */
    private void setNotification(String text, int code) {
        Notification notification = null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            //  // 创建通知渠道（适用于 Android 8.0 及以上版本）
            Uri mUri = Settings.System.DEFAULT_NOTIFICATION_URI;
            NotificationChannel mChannel = new NotificationChannel(CHANNEL_ONE_ID, "_channel_mqtt", NotificationManager.IMPORTANCE_LOW);
            mChannel.setDescription("mqtt service");
            mChannel.setSound(mUri, Notification.AUDIO_ATTRIBUTES_DEFAULT);
            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            manager.createNotificationChannel(mChannel);
            notification = new Notification.Builder(this, CHANNEL_ONE_ID)
                    .setChannelId(CHANNEL_ONE_ID)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText(text)
                    .build();
        } else {
            // 创建通知（适用于 Android 8.0 以下版本）
            notification = new Notification.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText(text)
                    .build();
        }
        // 设置通知标志
        notification.flags = Notification.FLAG_ONGOING_EVENT;
        notification.flags |= Notification.FLAG_NO_CLEAR;
        notification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
        startForeground(code, notification);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // 初始化通知
        initNotify();
        LogUtils.e("启动服务了");
        // 获取 MqttManager 单例实例
        mqttManager = MqttManager.getInstance();
        // 连接 MQTT
        mqttManager.connectMqtt();
        // 调度 MQTT Worker
        scheduleMqttWorker();
        return START_STICKY;
    }

    /**
     * 保活
     */
    private void initNotify() {
        // 显示通知
        setNotification("", GRAY_SERVICE_ID);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            LogUtils.e("关闭mqtt服务");
            // 断开 MQTT 连接
            if (mqttManager != null) {
                mqttManager.disconnectMqtt();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 使用 WorkManager 调度 MQTT 连接任务
     */
    private void scheduleMqttWorker() {
        // 设置任务的约束条件，要求网络连接可用。
        Constraints constraints = new Constraints.Builder()
                .setRequiredNetworkType(NetworkType.CONNECTED)
                .build();

        // 创建一个周期性任务，每隔 15 分钟执行一次
        PeriodicWorkRequest mqttWorkRequest = new PeriodicWorkRequest.Builder(
                MqttWorker.class, 15, TimeUnit.MINUTES)
                // ：设置任务的约束条件。
                .setConstraints(constraints)
                // 设置任务的约束条件。 配置重试策略。
                // BackoffPolicy.EXPONENTIAL 使用指数退避策略。 初始重试延迟为 10 秒，每次重试延迟时间会指数增长。
                .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 10, TimeUnit.SECONDS)
                .build();
        // 将任务添加到 WorkManager 中，并替换已存在的同名任务。
        WorkManager.getInstance(this).enqueueUniquePeriodicWork(MqttConfig.WORKER_NAME, ExistingPeriodicWorkPolicy.REPLACE, mqttWorkRequest);
    }

    /**
     *     初始化mqtt
     *      public void initMqtt() {
     *         Intent mqttService = new Intent(this, MqttService.class);
     *         startService(mqttService);
     *     }
     *
     *     mqtt连接状态
     *       @Subscribe(threadMode = ThreadMode.MAIN)
     *     public void onNetConnectSuccess(MqttConnectEvent mqttConnectEvent) {
     *         if (mqttConnectEvent.getState().equals("suc")) { // mqtt连接成功 可以做一些事
     *             MqttManager.subscribe("");
     *         }
     *     }
     */
    /**
     * 需要电池优化权限  安卓12以上
     *     Permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
     *     <uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
     *
     *    public boolean isIgnoringBatteryOptimizations(Context context) {
     *         PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
     *         return powerManager.isIgnoringBatteryOptimizations(context.getPackageName());
     *     }
     *
     *     public void requestIgnoreBatteryOptimizations(Context context) {
     *         if (!isIgnoringBatteryOptimizations(context)) {
     *             Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
     *                     .setData(Uri.parse("package:" + context.getPackageName()));
     *             if (intent.resolveActivity(context.getPackageManager()) != null) {
     *                 context.startActivity(intent);
     *             } else {
     *                 // 处理无法启动的情况（例如：设备不支持此功能）
     *                 Toast.makeText(context, "无法打开电池优化设置", Toast.LENGTH_SHORT).show();
     *             }
     *         } else {
     *             // 应用已经在白名单中
     *             Toast.makeText(context, "应用已在电池优化白名单中", Toast.LENGTH_SHORT).show();
     *         }
     *     }
     */

}
